import { WaterRecord } from '@/contexts/WaterIntakeContext';

// 本地存储键名
const RECORDS_KEY = 'waterIntakeRecords';
const GOAL_KEY = 'waterIntakeGoal';

// 数据库服务类
export class WaterDB {
  private static instance: WaterDB;
  
  // 单例模式
  private constructor() {}
  
  public static getInstance(): WaterDB {
    if (!WaterDB.instance) {
      WaterDB.instance = new WaterDB();
    }
    return WaterDB.instance;
  }
  
  // 获取所有喝水记录
  public getRecords(): WaterRecord[] {
    try {
      const recordsJson = localStorage.getItem(RECORDS_KEY);
      if (!recordsJson) return [];
      
      const records = JSON.parse(recordsJson);
      return records.map((record: any) => ({
        ...record,
        timestamp: new Date(record.timestamp)
      }));
    } catch (error) {
      console.error('Failed to get records from localStorage:', error);
      return [];
    }
  }
  
  // 添加喝水记录
  public addRecord(record: Omit<WaterRecord, 'id'> & { id?: string }): void {
    try {
      const id = record.id || Date.now().toString();
      const newRecord: WaterRecord = {
        id,
        ...record,
        timestamp: new Date(record.timestamp)
      };
      
      const records = this.getRecords();
      records.unshift(newRecord); // 添加到数组开头
      
      localStorage.setItem(RECORDS_KEY, JSON.stringify(records));
    } catch (error) {
      console.error('Failed to add record to localStorage:', error);
    }
  }
  
  // 获取每日目标
  public getDailyGoal(defaultGoal: number = 2000): number {
    try {
      const goalStr = localStorage.getItem(GOAL_KEY);
      if (!goalStr) return defaultGoal;
      
      const goal = parseInt(goalStr, 10);
      return isNaN(goal) ? defaultGoal : goal;
    } catch (error) {
      console.error('Failed to get daily goal from localStorage:', error);
      return defaultGoal;
    }
  }
  
  // 设置每日目标
  public setDailyGoal(goal: number): void {
    try {
      localStorage.setItem(GOAL_KEY, goal.toString());
    } catch (error) {
      console.error('Failed to set daily goal in localStorage:', error);
    }
  }
}

// 导出数据库实例
export const dbService = WaterDB.getInstance();